import numpy as np
import utils
import sys

def get_multi_src(src,size):
	ones=np.ones(size,dtype=np.int).reshape(size,1)
	return np.dot(ones,src)

def get_min_x_dist2(src,model,topn):
	# model.shape[0]=counter of the trainnnig pic's
	multi_src=get_multi_src(src,model.shape[0])
	distance_matrix=np.abs(multi_src-model)
	ones=np.ones(src.shape[1],dtype=np.int).reshape(src.shape[1],1)	
	dists=np.sort(np.dot(distance_matrix,ones).reshape(1,model.shape[0]))[0]
	return dists[:topn]



def find_label(img_vector,model,topn):
	result_arr=[]
	for j in range(model.shape[0]):
		current_topn=get_min_x_dist2(img_vector,model[j],topn)
		result_arr.append(current_topn)
	result=np.array(result_arr)
	sortted_topn=np.sort(result.reshape(1,model.shape[0]*topn)).reshape(model.shape[0],topn)
	coord=np.where(result<=sortted_topn[0][topn-1])[0]
	_c_max=0
	_c_max_index=-1
	for j1 in range(model.shape[0]):
		coord1=np.where(coord==j1)
		if coord1[0].size>0:
			_min=np.min(coord1[0])
			_max=np.max(coord1[0])
			_len=_max-_min
			if _len>=_c_max:
				_c_max=_len
				_c_max_index=j1
	return _c_max_index